<template>
  <div class="avatar">
    <el-avatar
      :size="35"
      :src="
        avatar
          ? avatar.replace(/public/, baseURL)
          : 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
      "
      @click="changeAvatar"
    >
    </el-avatar>
    <input type="file" ref="fileRef" @change="uploadFile" class="file" />
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { Ajax } from "../../api";
import { useStore } from "@/store";
const store = useStore();
import { baseURL } from "../../api/request";
defineProps({
  avatar: String,
});
const fileRef = ref<any>();
const changeAvatar = () => {
  fileRef.value.click(); //操作dom，模拟一个点击事件
};
const uploadFile = async () => {
  // console.log("开始上传")

  const filedata = fileRef.value.files[0];
  // console.log(filedata)

  const data = new FormData(); // 模拟一个JS 表单对象
  data.append("file", filedata); // 需要上传发送给服务器的数据

  let res: any = await Ajax.uploadfile(data);

  if (res.code == 200) {
    console.log(res);

    // 修改后端
    let data: any = await Ajax.changeuser({
      avatar: res.path, //给个人信息增加一个头像信息
    });
    // 再修改前端
    if (data.code == 200) {
      let userInfo = store.userInfo;
      userInfo.avatar = res.path;
      console.log(userInfo);
      store.setUserInfo(userInfo); //给个人信息增加一个头像信息
    }
  }
};
</script>

<style lang="scss" scoped>
.avatar {
  cursor: pointer;
  .file {
    display: none;
  }
}
</style>
